﻿namespace UnityEditor
{
    using System;
    using UnityEngine;

    internal class TreePlacementUtility
    {
        public static void PlaceRandomTrees(TerrainData terrainData, int treeCount)
        {
            int length = terrainData.treePrototypes.Length;
            if (length == 0)
            {
                Debug.Log("Can't place trees because no prototypes are defined");
            }
            else
            {
                Undo.RegisterUndo(terrainData, "Mass Place Trees");
                TreeInstance[] instanceArray = new TreeInstance[treeCount];
                int index = 0;
                while (index < instanceArray.Length)
                {
                    TreeInstance instance = new TreeInstance {
                        position = new Vector3(UnityEngine.Random.value, 0f, UnityEngine.Random.value)
                    };
                    if (terrainData.GetSteepness(instance.position.x, instance.position.z) < 30f)
                    {
                        Color color = Color.Lerp(Color.white, (Color) (Color.gray * 0.7f), UnityEngine.Random.value);
                        color.a = 1f;
                        instance.color = color;
                        instance.lightmapColor = Color.white;
                        instance.prototypeIndex = UnityEngine.Random.Range(0, length);
                        instance.widthScale = 1f;
                        instance.heightScale = 1f;
                        instanceArray[index] = instance;
                        index++;
                    }
                }
                terrainData.treeInstances = instanceArray;
                terrainData.RecalculateTreePositions();
            }
        }
    }
}

